#include "ota_http.h"

size_t get_text(char *ptr, size_t size, size_t nmemb, void *userdata)
{
    size_t size_all = size * nmemb;
    memcpy(userdata, ptr, size_all);
    ((char *)userdata)[size_all] = '\0';

    return size_all;
}
/**
 * @brief 获取文本
 *
 * @param url 要访问的地址
 * @return char* 获取到的文本数据
 */
char *ota_http_get_text(char *url)
{
    CURL *curl;
    // 全局环境初始化, 只需要初始化一次即可
    CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);

    // 初始化curl,得到curl局部
    curl = curl_easy_init();

    if (curl == NULL)
    {
        log_error("curl_easy_init() failed");
        return NULL;
    }

    // 设置要访问的url
    curl_easy_setopt(curl, CURLOPT_URL, url);

    // 设置回调函数, 接收访问到的值
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, get_text);

    // 设置回调函数的参数, 用来接收收到的数据
    char *buffer = (char *)malloc(1024);
    memset(buffer, 0, 1024);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, buffer);
    // 执行请求访问
    res = curl_easy_perform(curl);

    if (res != CURLE_OK)
    {
        log_error("curl_easy_perform() failed: %s", curl_easy_strerror(res));
        curl_easy_cleanup(curl);
        return NULL;
    }

    curl_easy_cleanup(curl);
    return buffer;
}

gate_state_t ota_http_download(char *url, char *file_path)
{
    CURL *curl;

    // 初始化curl,得到curl局部
    curl = curl_easy_init();

    if (curl == NULL)
    {
        log_error("curl_easy_init() failed");
        return GATE_ERROR;
    }

    // 设置要访问的url
    curl_easy_setopt(curl, CURLOPT_URL, url);

    // 设置回调函数, 获取文件数据
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite);

    FILE *fp = fopen(file_path, "wb");
    if (fp == NULL)
    {
        log_error("fopen() failed");
        curl_easy_cleanup(curl);
        return GATE_ERROR;
    }

    curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);

    CURLcode res = curl_easy_perform(curl);

    log_info("curl_easy_perform() res: %d", res);
    if (res != CURLE_OK)
    {

        log_error("curl_easy_perform() failed: %s", curl_easy_strerror(res));
        curl_easy_cleanup(curl);
        return GATE_ERROR;
    }

    long http_code = 0;
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
    if (http_code != 200)
    {
        log_error("http_code: %ld", http_code);
        return GATE_ERROR;
    }

    curl_easy_cleanup(curl);

    fclose(fp);

    return GATE_OK;
}
